package com.example.mykotlin.base.config

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.context.ApplicationListener
import org.springframework.context.event.ContextClosedEvent
import org.springframework.core.env.Environment
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Component


@Component
class MyCleanupBean(
    private val redisTemplate: RedisTemplate<String, Any>,
    private val environment: Environment,
) : ApplicationListener<ContextClosedEvent> {
    companion object {
        val log: Logger = LoggerFactory.getLogger(MyCleanupBean::class.java)
    }

    override fun onApplicationEvent(event: ContextClosedEvent) {
        val name = environment.getProperty("spring.application.name") ?: "poiuy"
        val idSetName = "${YitterIdInitConfig.ID_GENERATOR_KEY}:$name"
        log.info("清除本服务所用YitterId的workId {}", YitterIdInitConfig.getWorkId())
        redisTemplate.opsForSet().remove(idSetName, YitterIdInitConfig.getWorkId())
    }
}